// 表示层
var express = require("express");
var router = express.Router();
const postService = require("../service/postService");

// 新增帖子
router.post("/", async function (req, res) {
  let { poster, title, content, state, tags, comments, createTime } = req.body;
  let data = await postService.insert({
    poster,
    title,
    content,
    state,
    tags,
    comments,
    createTime,
  });
  res.send(data);
});

// 删除帖子
router.delete("/:id", async function (req, res) {
    let { id } = req.params;
    let data = await postService.delete(id);
    res.send(data);
});

// 查询所有帖子
router.get("/all", async function (req, res) {
  let data = await postService.findAll();
  console.log("data", data);
  res.send(data);
});

// 查询所有帖子并分页
router.get("/", async function (req, res) {
  let { type, value, current, pageSize } = req.query;
  let searchParams = {};
  searchParams[type] = new RegExp(value);
  let data = await postService.find(
    {
      current: current || 1,
      pageSize: pageSize,
    },
    searchParams
  );
  res.send(data);
});

// 按id查询帖子
router.get("/:id", async function (req, res) {
  let { id } = req.params;
  let data = await postService.findById(id);
  res.send(data);
});

// 修改帖子
router.put("/:id", async function (req, res) {
  let { id } = req.params;

  let { poster, title, content, state, tags, comments, createTime } = req.body;
  let data = await postService.update({
    _id: id,
    poster,
    title,
    content,
    state,
    tags,
    comments,
    createTime,
  });
  res.send(data);
});

module.exports = router;
